package middleware

import (
	"github.com/gin-gonic/gin"
	"perfect-admin/global"
	"perfect-admin/global/response"
	"perfect-admin/model/request"
	"perfect-admin/service"
	"strconv"
	"strings"
)

//拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, _ := c.Get("claims")
		user := claims.(*request.CustomClaims)
		//获取请求的URI
		obj := strings.Replace(c.Request.URL.Path, "/api/v1", "", 1)
		//获取请求方法
		act := c.Request.Method
		//获取用户的角色
		sub := strconv.Itoa(user.RoleId)

		e := service.Casbin()
		//判断策略中是否存在
		if global.CONFIG.System.Env == "develop" || user.RoleId == 1 || e.Enforce(sub, obj, act) {
			c.Next()
		} else {
			global.LOG.Warning(user.Username + "\t" + obj + "\t" + act + "非法请求\t权限不足")
			response.Response(c, 403, "权限不足", nil)
			c.Abort()
			return
		}
	}
}
